import { Component, Emit, Prop, Ref, Watch } from 'vue-facing-decorator'
import Render from '@/render/Render'
import toNative from '@/utils/toNative'
import TableRender from '@/render/TableRender'
import renderModal, { getModelValue, initModelValue, renderForm, type FormModalDto } from '@/components/modal/Modal'
import { addRole, getRoleMenuTree } from '@/api/system'
import type { RoleMenuDto } from '@/api/system/types'
import userStore from '@/stores/user'
import Dialog from '@/components/dialog/Index'
import { Button, message, Tree } from 'ant-design-vue'
import type { AntTreeDto } from '@/api/types'
import { createAntTreeKey } from '@/utils/util'

@Component
export class AddRole extends TableRender {
    @Prop() show!: boolean
    @Prop() roleId!: number
    
    @Ref treeRef = null as InstanceType<typeof Tree> | null

    showDialog = false

    menuData = [] as AntTreeDto<RoleMenuDto>[]

    checkKeys = [] as number[]

    allSonCheckedKeys = [] as number[]

    useStore = userStore()

    @Emit('update:show')
    updateShow(val: boolean) {
        return val
    }

    @Emit('refresh')
    handleRefresh() {}

    @Watch('show')
    async handleWatchShow(val: boolean) {
        this.showDialog = val
        this.show && await this.initRoleTreeData()
        this.basicForm = renderForm(this.basicFormConfig)
    }

    @Watch('showDialog')
    handleWatchShowDialog(val: boolean) {
        this.updateShow(val)
    }

    async initRoleTreeData() {
        const res = await getRoleMenuTree(this.roleId, this.useStore.userInfo.userId)
        this.getSonKeys(res.menus)
        
        this.menuData = createAntTreeKey<RoleMenuDto>(res.menus, 'id')
    }

    basicFormConfig = this.initFormConfig() as FormModalDto
    initFormConfig() {
        return {
            title: '新建角色',
            width: '500px',
            theme: 'light',
            show: false,
            spanAlign: 'left',
            items: {
                roleName: {
                    name: '名称',
                    element: 'input',
                    required: true
                },
                roleSort: {
                    name: '角色排序',
                    element: 'inputNumber',
                    defaultValue: 1,
                    params: {
                        min: 1
                    },
                    required: true
                },
                roleKey: {
                    name: '权限字符',
                    element: 'input',
                    required: true
                },
                menu: {
                    name: '权限配置',
                    element: 'checkbox',
                    params: {
                        label: '全选/全不选',
                    },
                    callback: {
                        change: (ev: boolean) => {
                            this.checkKeys = ev ? this.allSonCheckedKeys : []
                            // this.treeRef?.setCheckedKeys(ev ? this.allSonCheckedKeys : [])
                        }
                    }
                },
            },
            complete: async () => {
                this.basicFormConfig.show = false
            },
            cancel: () => {
                this.basicFormConfig.show = false
            },
            init: () => {
            }
        } as FormModalDto
    }
    basicForm = {
        validate: async () => {},
        clear: () => {},
        element: () => <> </>
    }

    
    /**
     * 获取checkedKeys里所有的子节点
     * @param menus
     * @returns
     */
    getSonKeys(menus: RoleMenuDto[]) {
        const res = [] as number[]
        const getSon = (menus: RoleMenuDto[]) => {
            for (const item of menus) {
                if (item.children?.length) {
                    getSon(item.children)
                } else {
                    this.allSonCheckedKeys.push(item.id)
                }
            }
        }
        getSon(menus)
        return res
    }

    onCancel() {
        this.showDialog = false
        this.basicForm.clear()
    }

    async onConfirm() {
        await this.basicForm.validate()
        const data = getModelValue(this.basicFormConfig)
        data.status = 0
        data.menuIds = this.checkKeys
        delete data.menu
        await addRole(data)
        message.success('添加成功')
        this.onCancel()
        this.handleRefresh()
    }

    render() {
        return <>
            <Dialog v-model:show={this.showDialog} alignCenter={true} title="新建角色" v-slots = {{
                default: () => {
                    return <>
                        { this.basicForm.element()}
                        <div class="h-400px overflow-auto p-l-20px -mt-20px">
                            <Tree
                                ref="treeRef"
                                class="w-full"
                                treeData={this.menuData}
                                checkable
                                fieldNames={{
                                    title: 'label',
                                    key: 'id'
                                }}
                                v-model:checkedKeys={this.checkKeys}
                                show-checkbox
                                defaultExpandAll={false}
                                checkStrictly={false}
                            ></Tree>
                        </div>
                    </>
                },
                footer: () => {
                    return <div class="flex justify-center">
                        <Button type="primary" onClick={this.onConfirm}>确定</Button>
                    </div>
                }
            }}>

            </Dialog>
        </>
    }
}

export default toNative<{roleId: number}, {refresh: () => void}>(AddRole)